package flexconsole.view {
	import flash.events.Event;
	
	import flexconsole.AppFacade;
	import flexconsole.ConfigKeys;
	import flexconsole.events.CheckAppUpdateEvent;
	import flexconsole.model.IConfigProxy;
	import flexconsole.model.WindowStateModel;
	import flexconsole.view.component.Preference;
	
	import flexunit.framework.Assert;
	
	import mx.events.AIREvent;
	import mx.events.PropertyChangeEvent;
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	public class PreferenceMediator extends Mediator {
		
		static public const DEFAULT_WIDTH:Number = 480;
		
		static public const DEFAULT_HEIGHT:Number = 240;
		
		static private var logger:ILogger = Log.getLogger("flexconsole.view.PreferenceMediator");
		
		protected var windowStateModel:WindowStateModel;
		
		private var isViewDirty:Boolean = false;
		
		public function PreferenceMediator(mediatorName:String = null, viewComponent:Object = null) {
			super(mediatorName, viewComponent);
		}
		
		public function get view():Preference {
			return viewComponent as Preference;
		}
		
		public function get appFacade():AppFacade {
			return facade as AppFacade;
		}
		
		override public function onRegister():void {
			logger.debug("onRegister()");
			super.onRegister();
			Assert.assertNotNull(appFacade);
			Assert.assertNotNull(view);
			windowStateModel = new WindowStateModel(appFacade.configProxy.getValue(ConfigKeys.WINDOW_STATE_PREFERENCE, null));
			windowStateModel.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onWindowStatePropertyChange);
			view.resourceBundle = appFacade.resourceBundle;
			view.addEventListener(Event.CLOSING, onWindowClosingEvent);
			view.addEventListener(AIREvent.WINDOW_DEACTIVATE, onWindowDeactiveEvent);
            view.addEventListener(CheckAppUpdateEvent.CHECK_UPDATE, onCheckAppUpdateEvent);

			updateView();
		}
		
		override public function listNotificationInterests():Array {
			return [ AppFacade.PREFERENCE, AppFacade.SHUTDOWN, AppFacade.DATA_CHANGE ];
		}
		
		override public function handleNotification(notification:INotification):void {
			if (AppFacade.PROXYNAME_CONFIG == notification.getType()) {
				if (notification.getBody() == null) {
					// full refresh
					invalidateView();
				} else {
					//  config has changed, we watch the following key changes
					switch (notification.getBody()) {
						case ConfigKeys.CONNECTION_NAME:
						case ConfigKeys.MAX_LOG_NUM:
						case ConfigKeys.CHECK_UPDATE_ON_STARTUP:
						case ConfigKeys.CHECK_UPDATE_STATUS:
							invalidateView();
							break;
					}
				}
			} else if (AppFacade.PREFERENCE == notification.getName()) {
				//  show window
				if (!view.nativeWindow) {
					view.open(true);
					windowStateModel.target = view.nativeWindow;
				} else {
					view.activate();
					view.visible = true;
				}
				updateView();
			} else if (AppFacade.SHUTDOWN == notification.getName()) {
				view.removeEventListener(Event.CLOSING, onWindowClosingEvent);
				if (view.nativeWindow) {
                    save();
					view.close();
				}
			}
		}
		
		protected function invalidateView():void {
			if (view && !isViewDirty) {
				isViewDirty = true;
				view.callLater(updateView);
			}
		}
		
		protected function updateView():void {
			logger.debug("updateView()");
			isViewDirty = false;
			var configProxy:IConfigProxy = appFacade.configProxy;
			var obj:Object = configProxy.getValue(ConfigKeys.WINDOW_STATE_PREFERENCE, null);
			
			if (obj) {
				windowStateModel.read(obj);
				windowStateModel.updateTarget();
			}
			//   Fixed size.
			view.width = DEFAULT_WIDTH;
			view.height = DEFAULT_HEIGHT;
			view.connectionName = configProxy.getValue(ConfigKeys.CONNECTION_NAME, "_mdbtrace");
			view.maxLogNum = configProxy.getValue(ConfigKeys.MAX_LOG_NUM, 1000);
			view.checkAppUpdateStatus = configProxy.getValue(ConfigKeys.CHECK_UPDATE_STATUS, " ");
			view.checkAppUpdateOnStartup = configProxy.getValue(ConfigKeys.CHECK_UPDATE_ON_STARTUP, true);
		
		}
		
		protected function onWindowClosingEvent(event:Event):void {
			logger.debug("onWindowClosingEvent({0})", event);
			
			if (view.visible) {
				event.preventDefault();
				close();
			}
		}
		
		protected function onWindowDeactiveEvent(event:Event):void {
			logger.debug("onWindowDeactiveEvent({0})", event);
			save();
		}
		
		protected function onWindowStatePropertyChange(event:PropertyChangeEvent):void {
			logger.debug("onWindowStatePropertyChange({0})", event);
			appFacade.configProxy.setValue(ConfigKeys.WINDOW_STATE_PREFERENCE, windowStateModel.write());
		}
		
		protected function close():void {
			logger.debug("close()");
			view.visible = false;
			view.orderToBack();
			save();
		}
		
		protected function save():void {
			logger.debug("save()");
			var configProxy:IConfigProxy = appFacade.configProxy;
			configProxy.setValue(ConfigKeys.CONNECTION_NAME, view.connectionName);
			configProxy.setValue(ConfigKeys.MAX_LOG_NUM, view.maxLogNum);
			configProxy.setValue(ConfigKeys.CHECK_UPDATE_ON_STARTUP, view.checkAppUpdateOnStartup);
		}
		
		
        protected function onCheckAppUpdateEvent(event:CheckAppUpdateEvent):void {
            sendNotification(AppFacade.CHECK_APP_UPDATE);
        }
	}
}

